/**
 * Copyright ©2003~2019年4月30日 szkingdom
 * @author raohj
 * @date 2019年4月30日
 * @file RThreadLock.java
 * @comment : please input your comment to this file
 * @version : input version
 * @modify:
 * 		1、 2019年4月30日 由 raohj 新建文件
 */
package com.ccnu.demojava.concurrent.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author raohj
 * @date 2019年4月30日
 * @version 
 * @comment to add your comment
 */
public class RReentrantLock{
	private static final Logger log = LoggerFactory.getLogger(RReentrantLock.class);
	public static class RLockRunnable implements Runnable{
		public static ReentrantLock lock = new ReentrantLock(true);
		public static volatile int i = 0;
		@Override
		public void run() {
			while(i<100) {
				lock.lock();
				try {
					log.info("begin to sleep");
					Thread.sleep(10000);
					if(i>=100) {
						return;
					}
					i++;
					log.info("[" + Thread.currentThread().threadId() + "]" + " sales:" + i);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void test() {
		ExecutorService es = Executors.newFixedThreadPool(10);
		for(int i=0; i<2; i++) {
			es.submit(new RLockRunnable());
		}
		es.shutdown();
	}
}
